package com.zzfeidu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.zzfeidu.pojo.N1Record;
import com.zzfeidu.pojo.Qmessage;
import com.zzfeidu.service.IN1RecordService;
import com.zzfeidu.service.IQmessageService;
import com.zzfeidu.utils.SnowFlake;
import org.jsoup.helper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@RestController
public class MQController {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Reference
    private IQmessageService qmessageService;

    @Reference
    private IN1RecordService recordService;

    private static final String DESTINATION = "mq.queue";

    private static final Logger logger = LoggerFactory.getLogger(MQController.class);

    SnowFlake snowFlake = new SnowFlake(1, 1);

    @RequestMapping("/test")
    public Object test(){
        return qmessageService.selectQmessageList(null);
//        return mqProducer.test();
    }
    @RequestMapping("/test2")
    public Object test2(){
        return recordService.selectN1RecordList(null);
//        return mqProducer.test2();
    }

    /**
     * 注意这里：分布式是拿不到插入数据库时返回的自增id的，所以这里需要
     * 用雪花算法计算一个全局唯一性的ID来放入数据，以后的操作都通过这个ID
     * @return
     */
    @RequestMapping("/test3")
    @Transactional
    public Object test3(){
        // 先db操作
        Qmessage qmessage = new Qmessage();
        // 消息内容
        String message = "{\"url\":\"http://www.abidu.com\",\"data\":\"a=1&b=2\"}";
        qmessage.setMessageContent(message);
        qmessage.setDestination(DESTINATION);
        qmessage.setDestType(0);
        long nextId = snowFlake.nextId();
        qmessage.setMessageId(nextId + "");
        qmessage.setTimeStamp(System.currentTimeMillis());
        qmessageService.insertQmessage(qmessage);
        jmsTemplate.convertAndSend(DESTINATION,nextId);
//        jmsTemplate.send(DESTINATION, new MessageCreator() {
//            @Override
//            public Message createMessage(Session session) throws JMSException {
//                return session.createTextMessage(qmessage.getId().toString());
//            }
//        });
        return"true";
    }


    /**
     * 生成消息
     * @param addr
     */
//    @Transactional
    public void sendOrderMessage(String addr) {
        // 先db操作
        Qmessage qmessage = new Qmessage();
        // 消息内容
        qmessage.setMessageContent(addr);
        qmessage.setDestination(DESTINATION);
        qmessage.setDestType(0);
        qmessage.setTimeStamp(System.currentTimeMillis());
        qmessageService.insertQmessage(qmessage);
        jmsTemplate.convertAndSend(DESTINATION,qmessage.getId());
    }

    @JmsListener(destination = DESTINATION)
    public void receiveOrder1(final String message) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 不为空
        if(!StringUtil.isBlank(message)){
            // 消息本体
            Qmessage qmessage = qmessageService.selectQmessageByMessageId(message);
            // 是否消费过
            N1Record n1Record = recordService.selectN1RecordById(message);
            if(qmessage!=null){
                if(n1Record==null){
                    // 这里走业务逻辑  注意添加事务
                    qmessage.setDestination("");
                    qmessage.setStatus(1);
                    qmessageService.updateQmessage(qmessage);

                    N1Record n1Records = new N1Record();
                    n1Records.setMessageId(message);
                    n1Records.setTimeStamp(System.currentTimeMillis());
                    recordService.insertN1Record(n1Records);
                    // 发送消息

                    JSONObject dataObj = JSONObject.parseObject(qmessage.getMessageContent());
                    String url = dataObj.getString("url");
                    String data = dataObj.getString("data");
                    if(!StringUtil.isBlank(data)){
                        // 发送post
                        String[] strs = data.split("&");
                        Map<String, String> params = new HashMap<>();
                        for(int i = 0 ; i < strs.length; i ++){
                            String[] ss = strs[i].split("=");
                            if(ss.length==2){
                                params.put(ss[0],ss[1]);
                            }
                        }
//                        HttpUtils.httpPost(url,params);
                        System.out.println(1);
                    }else{
                        // 发送get
//                        HttpUtils.httpGET(url);
                        System.out.println(2);
                    }


                } else {
                    System.out.println("消息已经消费过了");
                }
            }else{
                System.out.println("消息不存在");
            }
        }
        logger.info("1");
    }
}
